package com.feishi.core.analytic.element;

import com.feishi.core.analytic.PoType;
import com.feishi.core.analytic.body.AnalyticBody;

import java.util.*;

/**
 * Created by caixq on 5/4 004.
 */
public class AnalyticContentMapElement extends AnalyticContentElement {

    public AnalyticContentMapElement() {
        init(String.valueOf(PoType.ELEMENT_CONTENT),PoType.ELEMENT_CONTENT);
    }
    public AnalyticContentMapElement(String name) {
        init(name,PoType.ELEMENT_CONTENT);
    }

    private void init(String name, int type) {
        this.type=type;
        this.name=name;
    }

    Map<Object,AnalyticBody> defaultMap =new HashMap<>();
    Map<String,Map<Object,AnalyticBody> > contentMap=new HashMap<>();

    private AnalyticBody defaultAnalyticBody=new AnalyticBody();

    public AnalyticBody getBody(Map<String,Object> typeMap) {
        AnalyticBody body=null;
        if(contentTypeList.size()==1){
            body= defaultMap.get(contentTypeList.get(0).getValue((byte[]) typeMap.get(contentTypeList.get(0).getName())));
        }else{
            for(AnalyticStaticContentTypeDataElement contentType:contentTypeList){
                Map<Object,AnalyticBody> map=contentMap.get(contentType.getName());
                if(map==null){
                    continue;
                }
                body= map.get(contentType.getValue((byte[]) typeMap.get(contentType.getName())));
                if(body!=null){
                    break;
                }
            }

        }
        if(body!=null){
            return body;
        }
        return defaultAnalyticBody;
    }
//    public void setRefer(AnalyticStaticContentTypeDataElement contentType, AnalyticStaticInputDataElement contentLength, AnalyticStaticInputDataElement contentEncode) {
//        this.contentType=contentType;
//        this.contentLength=contentLength;
//        this.contentEncode=contentEncode;
//    }

    public void put(Object key, AnalyticBody body) {
        defaultMap.put(key,body);
    }


    public void init(List<AnalyticStaticContentTypeDataElement> contentTypes, AnalyticStaticInputDataElement contentLength, AnalyticStaticInputDataElement contentEncode) {
        this.contentTypeList=contentTypes;
        Collections.sort(contentTypeList);
        for (AnalyticStaticContentTypeDataElement contentType:contentTypeList) {
            this.contentTypeMap.put(contentType.getName(),contentType);
        }

        this.contentLength=contentLength;
        this.contentEncode= (AnalyticStaticContentEncodeDataElement) contentEncode;
    }

    public void put(String typeName, Object key, AnalyticBody body) {
        Map<Object, AnalyticBody> map = contentMap.get(typeName);
        if(map==null){
            map=new HashMap<>();
            contentMap.put(typeName,map);
        }
        map.put(key,body);
    }
}
